<template>
  <div class="project-setting-view">
    <div class="project-setting-title">
      {{ $t("form.setting.notificationSettingLabel") }}
      <span class="small-font-size ml20 text-secondary-color">{{ $t("form.setting.notifySettingSubtitle") }}</span>
    </div>
    <el-divider />
    <el-form
      ref="notifySettingFormRef"
      :model="settingConf"
      :rules="settingRules"
    >
      <div class="setting-item">
        <p class="label">{{ $t("form.setting.newDataEmailNotification") }}</p>
        <el-switch
          v-model="settingConf.emailNotify"
          @change="saveSettingHandle"
        />
      </div>
      <el-form-item
        v-if="settingConf.emailNotify"
        class="pb10"
        prop="newWriteNotifyEmail"
      >
        <el-row :gutter="20">
          <el-col :span="14">
            <el-input
              @change="saveSettingHandle"
              v-model="settingConf.newWriteNotifyEmail"
              :placeholder="$t('form.setting.newDataEmailInputPlaceholder')"
            />
          </el-col>
          <el-col :span="2">
            <el-button @click="handleOpenUserTable">{{ $t("form.setting.chooseSystemUsers") }}</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <div class="setting-item">
        <p class="label">{{ $t("form.setting.newDataWeChatNotification") }}</p>
        <el-switch
          v-model="settingConf.wxNotify"
          @change="saveSettingHandle"
        />
      </div>
      <p
        class="project-setting-sub-label sub-label-text"
        v-if="settingConf.wxNotify"
      >
        {{ $t("form.setting.followOfficialAccount") }}
        <el-link
          type="primary"
          @click="openSubNotifyWxDialogHandle"
        >
          {{ $t("form.setting.clickToFollow") }}
        </el-link>
      </p>
      <el-row
        v-if="settingConf.newWriteNotifyWx"
        align="middle"
        type="flex"
      >
        <el-col
          :offset="3"
          :span="5"
        >
          <p class="project-setting-sub-label">{{ $t("form.setting.notificationRecipients") }}</p>
        </el-col>
        <el-col :span="12">
          <span
            v-for="(user, i) in subNotifyWxUserList"
            :key="i"
            class="sub-user-view"
          >
            <el-icon
              class="sub-user-delete"
              @click="deleteSubNotifyUserHandle"
            >
              <ele-Close />
            </el-icon>
            <el-avatar :src="user.headImgUrl" />
            <span>{{ user.nickname }}</span>
          </span>
        </el-col>
      </el-row>
      <el-dialog
        v-model="dialogSubNotifyVisible"
        :title="$t('form.setting.subscribeWeChatQRCodeTitle')"
        width="400px"
      >
        <el-image
          :src="subNotifyWxQrCode"
          fit="fill"
          style="width: 150px; height: 150px"
        />
      </el-dialog>
    </el-form>
    <!--    用户选择-->
    <user-choose-table
      ref="userChooseTableRef"
      @submit="handleSelectUser"
    />
  </div>
</template>

<script setup lang="ts" name="NotifySetting">
import { onMounted, onUnmounted, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { deleteWxNotifyUserRequest, getWxNotifyQrcodeRequest, getWxNotifyUserRequest } from "@/api/project/setting";
import { useRoute } from "vue-router";
import { i18n } from "@/i18n";
import { loadAsyncComponent } from "@/utils/asyncComponent";

const UserChooseTable = loadAsyncComponent(() => import("@/views/system/user/chooseTable.vue"));

const settingRules = ref<FormRules>({
  newWriteNotifyEmail: [
    {
      trigger: "blur",
      pattern: /^((([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6}\;))*(([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})))$/,
      message: i18n.global.t("form.setting.enterEmail")
    },
    { required: true, message: i18n.global.t("form.setting.enterEmail"), trigger: "blur" }
  ]
});

const props = defineProps({
  settingConf: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(["update"]);

const dialogSubNotifyVisible = ref(false);
const subNotifyWxQrCode = ref("");

interface WxUser {
  openId: string;
  nickname: string;
  headImgUrl: string;
}

const subNotifyWxUserList = ref<WxUser[]>([]);
let subNotifyUserTimer = ref<NodeJS.Timeout | null>(null);

const route = useRoute();

const formKey = ref(route.query.key); // Ensure formKey is initialized properly

onMounted(async () => {
  if (props.settingConf.newWriteNotifyWx) {
    await querySubNotifyWxUser(props.settingConf.newWriteNotifyWx);
  }
  await getSubNotifyWxQrCode();
});

onUnmounted(() => {
  subNotifyUserTimer.value && clearInterval(subNotifyUserTimer.value);
});

const openSubNotifyWxDialogHandle = () => {
  dialogSubNotifyVisible.value = true;
  subNotifyUserTimer.value = setInterval(() => {
    querySubNotifyWxUser();
  }, 5000);
};

const querySubNotifyWxUser = async (openIdStr = "") => {
  const res = await getWxNotifyUserRequest({ key: formKey.value, openIdStr });
  subNotifyWxUserList.value = res.data;
  if (subNotifyWxUserList.value) {
    const changeNewWriteNotifyWx = subNotifyWxUserList.value.map(item => item.openId).join(";");
    if (!openIdStr && changeNewWriteNotifyWx !== props.settingConf.newWriteNotifyWx) {
      props.settingConf.newWriteNotifyWx = changeNewWriteNotifyWx;
      await saveSettingHandle();
      dialogSubNotifyVisible.value = false;
    }
  }
};

const getSubNotifyWxQrCode = async () => {
  const res = await getWxNotifyQrcodeRequest({ key: formKey.value });
  subNotifyWxQrCode.value = res.data;
};

const deleteSubNotifyUserHandle = async (i: number) => {
  if (subNotifyWxUserList.value && i >= 0 && i < subNotifyWxUserList.value.length) {
    const openId = subNotifyWxUserList.value[i].openId;
    await deleteWxNotifyUserRequest(formKey.value as string, openId);
    subNotifyWxUserList.value.splice(i, 1);
    props.settingConf.newWriteNotifyWx = subNotifyWxUserList.value.map(item => item.openId).join(";");
    await saveSettingHandle();
  }
};

const notifySettingFormRef = ref<FormInstance | null>(null);

const saveSettingHandle = async () => {
  notifySettingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      emit("update", props.settingConf);
    } else {
      return false;
    }
  });
};

const handleSelectUser = (list: any[]) => {
  if (list && list.length) {
    let emails = list
      .filter(user => {
        return user.email;
      })
      .map(user => user.email)
      .join(";");
    props.settingConf.newWriteNotifyEmail = props.settingConf.newWriteNotifyEmail || "" + emails;
    saveSettingHandle();
  }
};

const userChooseTableRef = ref<InstanceType<typeof UserChooseTable> | null>(null);

const handleOpenUserTable = () => {
  userChooseTableRef.value!.showDialog([]);
};
</script>

<style lang="scss" scoped>
@use "settting" as *;

.sub-label-text {
  text-align: left;
}

.sub-user-view {
  position: relative;
  display: inline-block;
  height: 100%;
  width: 60px;
  cursor: pointer;

  &:hover .sub-user-delete {
    display: block;
  }

  .sub-user-delete {
    position: absolute;
    right: -6px;
    background-color: red;
    color: white;
    border-radius: 50px;
    padding: 2px;
    font-size: 12px;
    height: 16px;
    width: 16px;
    font-weight: 500;
    line-height: 18px;
    display: none;
  }
}
</style>
